﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Dooshion.Utility
{
    public class IOHelper
    {
        /// <summary>
        /// 清理系统临时缓存目录默认在~/Temp
        /// </summary>
        /// <param name="fileType">指定文件扩展名</param>
        /// <param name="preMinute">当前时间前多少分钟值</param>
        public static void DelTempFile(string fileType, int preMinute)
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath("~/");
                DirectoryInfo di = new DirectoryInfo(path + "Temp");
                FileInfo[] fi = di.GetFiles("*." + fileType);
                DateTime dtNow = DateTime.Now;
                foreach (FileInfo tmpfi in fi)
                {
                    TimeSpan ts = dtNow.Subtract(tmpfi.LastWriteTime);
                    if (ts.TotalMinutes > preMinute)
                    {
                        tmpfi.Delete();//删除文件
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void WriteTxt(string content, string path)
        {
            if (!FileIsExist(path))
            {
                CreateFile(path);
            }
            using (StreamWriter sr = new StreamWriter(path, true, System.Text.Encoding.GetEncoding("GB2312")))
            {
                sr.WriteLine("\n");
                sr.WriteLine("***************************************************************");
                sr.WriteLine(content);
                sr.Close();
            }
        }


        public static void CreateFile(string path)
        {
            using (StreamWriter sr = File.CreateText(path))
            {
                sr.Close();
            }
        }

        public static bool FileIsExist(string path)
        {
            return File.Exists(path);
        }
    }
}
